<!-- subpkg_medicine/payment/index.vue -->
<script lang="ts" setup>
import { getAddressListApi } from "@/apis/address"
import { createUnpaidOrderApi, preOrderApi } from "@/apis/order"
import type { Address } from "@/types/address"
import type { OrderPre } from "@/types/order"
import { ref } from "vue"
import CustomPayment from "@/components/custom-payment/custom-payment.vue"
import type { CustomPaymentInstance } from "@/types/components"
import { orderPayApi } from "@/apis/pay"

// 1. 收货地址信息
const addressInfo = ref<Address>()
// 用户收货地址
const getAddressList = async () => {
  // 地址列表接口
  const res = await getAddressListApi()
  // 渲染地址列表数据
  addressInfo.value = res.find((item) => item.isDefault)
}
// 获取收货地址列表
getAddressList()

// 2. 预付订单
const pageParams = defineProps<{
  id: string // 处方id
}>()
// 预付订单信息
const preOrderInfo = ref<OrderPre>()
// 药品预付订单
const getPreOrder = async () => {
  if (!pageParams.id) return
  // 预付订单接口
  const res = await preOrderApi(pageParams.id)
  // 渲染预付订单信息
  preOrderInfo.value = res
}
// 获取预付订单
getPreOrder()

// 3. 待支付订单ID
const orderId = ref("")
// 支付渠道组件实例
const paymentRef = ref<CustomPaymentInstance>()
// 确认支付回调
const onPaymentConfirm = async (index: number) => {
  if (index === 0)
    return uni.showToast({ title: "暂不支持微信支付", icon: "none" })
  // 支付
  const res = await orderPayApi({
    orderId: orderId.value,
    paymentMethod: index.toString(),
    payCallback: "http://localhost:5173/#/subpkg_medicine/pay_result/index",
  })
  // 支付宝支付页面
  window.location.href = res.payUrl
}
// 关闭支付回调
const onPaymentClose = () => {
  paymentRef.value?.close()
}
// 选择支付渠道
const onPaymentButtonClick = async () => {
  // 无收货地址提醒
  if (!addressInfo.value) {
    return uni.showToast({ title: "请添加收货地址", icon: "none" })
  }
  // 没有订单id
  if (orderId.value === "") {
    // 创建待支付订单
    const res = await createUnpaidOrderApi(pageParams.id, addressInfo.value.id)
    // 保存订单id
    orderId.value = res.id
    console.log(res)
  }
  paymentRef.value?.open()
}
</script>

<template>
  <scroll-view background-color="#f6f6f6">
    <view class="medicine-page">
      <view class="page-header">
        <view v-if="addressInfo?.id" class="order-shippment">
          <view class="region">
            <uni-icons size="16" color="#FF7702" type="location-filled" />
            {{ addressInfo.province }}{{ addressInfo.city }}
          </view>
          <view class="detail">{{ addressInfo.addressDetail }}</view>
          <view class="receiver"
            >{{ addressInfo.receiver }} {{ addressInfo.mobile }}</view
          >
        </view>
        <view v-else class="order-shippment">
          <uni-icons size="24" color="#999999" type="location-filled" />
          <text>请添加收货地址</text>
        </view>
      </view>

      <view class="order-shop">
        优医药房
        <text class="alt">优医质保 假一赔十</text>
      </view>
      <!-- 药品列表 -->
      <view class="medicine-list">
        <view
          class="medicine-list-item"
          v-for="item in preOrderInfo?.medicines"
          :key="item.id"
        >
          <image class="medicine-cover" :src="item.avatar" mode="aspectFill" />
          <view class="medicine-info">
            <text class="name">{{ item.name }}</text>
            <text class="unit" :class="{ symbol: item.prescriptionFlag === 1 }">
              {{ item.specs }}
            </text>
            <text class="price">¥{{ item.amount }}</text>
          </view>
          <view class="quantity">x{{ item.quantity }}</view>
          <view class="guide">用法用量：{{ item.usageDosag }}</view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="order-info" v-if="preOrderInfo?.id">
        <uni-list :border="false">
          <uni-list-item
            title="药品金额"
            :right-text="`¥${preOrderInfo.payment}`"
          />
          <uni-list-item
            title="运费"
            :right-text="`¥${preOrderInfo.expressFee}`"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${preOrderInfo.couponDeduction}`"
          />
          <uni-list-item
            title="实付款"
            :right-text="`¥${preOrderInfo.actualPayment}`"
          />
        </uni-list>
      </view>

      <!-- 底部 -->
      <view class="toolbar" v-if="preOrderInfo?.id">
        <view class="total-amount">
          需付款: <text class="number">¥{{ preOrderInfo.actualPayment }}</text>
        </view>
        <view class="buttons">
          <button class="uni-button" @click="onPaymentButtonClick">
            立即支付
          </button>
        </view>
      </view>
    </view>
    <CustomPayment
      v-if="preOrderInfo?.actualPayment"
      @confirm="onPaymentConfirm"
      @close="onPaymentClose"
      :order-id="orderId"
      :amount="preOrderInfo.actualPayment"
      ref="paymentRef"
    />
  </scroll-view>
</template>

<style lang="scss">
@import "./index.scss";
</style>
